<?php
!defined('IN_ZHUSHOU') && exit('Access Denied');

class NoticeModel extends CacheBaseModel
{
	// 消息表, 日后可以根据uid进行分表
	const NOTICE_TABLE = 'notices';

	public function __construct()
	{
		parent::__construct();
	}

	public static $MSG_TPYES = array( 
        1 => array(
            'types' => array(
                11 => array('desc' => '评论回复', 'msg_type' => 4, 'sub_channel' => 1000),
                12 => array('desc' => '评论赞', 'msg_type' => 2, 'sub_channel' => 1000),
            ),
            'desc' => 'App评论',
        ),
        2 => array(
            'types' => array(
                21 => array('desc' => '推荐被评论', 'msg_type' => 1, 'sub_channel' => 0),
                22 => array('desc' => '推荐被点赞', 'msg_type' => 2, 'sub_channel' => 0),
                23 => array('desc' => '推荐的评论被回复', 'msg_type' => 4, 'sub_channel' => 1000),
                24 => array('desc' => '推荐的回帖的评论被删除', 'msg_type' => 3, 'sub_channel' => 1000),
                25 => array('desc' => '推荐的回帖被删除', 'msg_type' => 3, 'sub_channel' => 1000),
                // 26 => array('desc' => '推荐被管理员删除'),
                // 27 => array('desc' => '推荐里的评论被管理员删除'),
            ),
            'desc' => '话题相关',
        ),
        3 => array(
            'types' => array(
                31 => array('desc' => '分享被评论', 'msg_type' => 1, 'sub_channel' => 0),
                32 => array('desc' => '分享被点赞', 'msg_type' => 2, 'sub_channel' => 0),
                33 => array('desc' => '分享被回复', 'msg_type' => 4, 'sub_channel' => 1000),
            ),
            'desc' => '分享App',
        ),
        4 => array(
            'types' => array(
                41 => array('desc' => '专题被评论', 'msg_type' => 1, 'sub_channel' => 0),
                42 => array('desc' => '专题被点赞', 'msg_type' => 2, 'sub_channel' => 0),
                43 => array('desc' => '专题评论被回复', 'msg_type' => 4, 'sub_channel' => 1000),
            ),
            'desc' => '专题相关',
        ),
        5 => array(
            'types' => array(
                51 => array('desc' => '评论', 'msg_type' => 1, 'sub_channel' => 0),
                52 => array('desc' => '点赞', 'msg_type' => 2, 'sub_channel' => 0),
                53 => array('desc' => '回复', 'msg_type' => 4, 'sub_channel' => 1000),
            ),
            'desc' => 'unknow',
        ),
        6 => array(
            'types' => array(
                61 => array('desc' => '提醒', 'msg_type' => 5, 'sub_channel' => 0),
            ),
            'desc' => '关注',
        ),
    );

	public function validateMsgType($channel, $type)
	{
		return isset(self::$MSG_TPYES[$channel]['types'][$type]);
	}

	// 发送消息, 注意用签名校验, 防止重放
	public function send($from, $to, $channel, $type, $relate)
	{
		$typeInfo = self::$MSG_TPYES[$channel]['types'][$type];
		return $this->add(array(
							'from_uid' => $from, 
							'to_uid' => $to, 
							'notice_channel' => $channel, 
							'notice_type' => $type, 
							'sub_channel' => intval($typeInfo['sub_channel']), 
                            'msg_type' => intval($typeInfo['msg_type']), 
							'relate_id' => $relate, 
							'notice_time' => date('Y-m-d H:i:s')
						), 
						self::NOTICE_TABLE);
	}

	/**
	 * 验证消息逻辑
	 *
	 * @author lijie
	 * @date   2015-05-12
	 */
	public function validateMessage($from, $to, $channel, $type)
	{
		if(!$this->validateMsgType($channel, $type)) 
        {
            return array('status' => -5, 'message' => 'Invalid Channel Or Type');
        }

        if ($from > 0)
        {
            $isValid = UserProxy::isValidQid($from);
            if (!$isValid)
            {
                return array('status' => -3, 'message' => 'From User Invalid');
            }
        }
        $isValid = UserProxy::isValidQid($to);
        if (!$isValid)
        {
            return array('status' => -4, 'message' => 'To User Invalid');
        }
		return array('status' => 1, 'message' => 'Ok');
	}

	// 获取个数
	public function getCount($to, $channel = 0, $status = -1)
	{
		$sql = "select count(*) from ".self::NOTICE_TABLE." where to_uid=".intval($to);

		if ($channel != 0)
		{
			$sql .= " and notice_channel=".intval($channel);
		}
		else
		{
			$sql .= " and notice_channel in(1,2,3,4,5) and notice_type in(11,12,21,22,23,31,32,33,41,42,43)";
		}

		if ($status > -1)
		{
			$sql .= " and status=".intval($status);
		}

		$result = $this->execute($sql);
		$ret = $result->fetchArray(MYSQL_NUM);
		return $ret[0];
	}

	// 获取分组个数
	public function getGroupCount($to, $status = -1)
	{
		$statusSql = '';
		if ($status > -1)
		{
			$statusSql = ' And status=' . $status;
		}

		$sql        = 'SELECT notice_channel AS channel, COUNT(*) AS num FROM ' . self::NOTICE_TABLE . ' WHERE to_uid=' . $to . $statusSql . ' GROUP BY notice_channel';
		$result     = $this->getManyByQuery($sql);
		$groupCount = array();
		if (is_array($result))
		{
			foreach ($result as $item)
			{
				$groupCount[$item['channel']] = $item['num'];
			}
		}
		return $groupCount;
	}

	// 获取列表
	public function getList($to, $channel = 0, $status = -1)
	{
		$channelSql = '';
		if ( is_numeric($channel) && $channel > 0 )
		{
			$channelSql = ' AND notice_channel = ' . intval($channel);
		}
		$statusSql = '';
		if (is_numeric($status) && $status >= 0)
		{
			$statusSql = ' AND status = ' . intval($status);
		}
		$sql  = '/*master*/ SELECT * FROM ' . self::NOTICE_TABLE . ' WHERE to_uid=' . intval($to) . $channelSql . $statusSql.' order by notice_id desc limit 100';
		$list = $this->getManyByQuery($sql);
		return $list;
	}

	// 设定已读状态
	public function setRead($ids)
	{
		if (is_array($ids) && sizeof($ids) > 0)
		{
			$sql = 'Update ' . self::NOTICE_TABLE . ' SET status=1 WHERE notice_id IN (' . implode(',', $ids) . ')';
			$this->execute($sql);
		}
		return True;
	}

	// 根据回复或者评论ID获取app的信息
	public function getAppInfos($commentIds)
	{
		$sql = 'SELECT object_id, comment_id FROM comment_meta WHERE comment_id in (' . implode(',' , $commentIds) . ')';
		$items = $this->getManyByQuery($sql);
		$pair = array();
		$sids = array();
		if (is_array($items) && sizeof($items) > 0)
		{
			foreach ($items as $item)
			{
				$pair[$item['comment_id']] = $item['object_id'];
				$sids[$item['object_id']] = 1;
			}
			$sids = implode('|', array_keys($sids));
			$url  = 'http://openbox.mobilem.360.cn/index/getSoftInfoByIdsAccordingToFields/sids/' . $sids . '/fields/soft_id%7Csoft_name%7Clogo_url%7Cpname';
			$json = Utility::getUrlContents($url, 3);
			$apps = json_decode($json, True);
			foreach ($pair as $commentId => $sid)
			{
				if (isset($apps[$sid]))
				{
					$pair[$commentId] = $apps[$sid];
				}
			}
		}
		return $pair;
	}

	// 根据推荐ID获取话题信息
	public function getTopics($rids)
	{
		if (RUN_MODE == 'test')
		{
			$host = '123.125.83.240';
			$header = array('Host:openbox.mobilem.360.cn');
		}
		else
		{
			$host = 'openbox.mobilem.360.cn';
			$header = array();
		}
		$url = 'http://' . $host . '/topic/getTopicByRecommid?recomm_ids=' . implode(',', $rids);
		$json = Utility::getUrlContents($url, 3, $header);
		$topics = json_decode($json, True);
		if (is_array($topics) && isset($topics['status']) && $topics['status'] == 1)
		{
			$topics = $topics['topic'];
		}
		return $topics;
	}

	// 调用林哲接口, 获取用户分享的app
	public function getShares($sids, $channel = 3)
	{
		if (RUN_MODE == 'test')
		{
			$host = '123.125.83.240';
			$header = array('Host:openbox.mobilem.360.cn');
		}
		else
		{
			$host = 'openbox.mobilem.360.cn';
			$header = array();
		}
		$url    = 'http://' . $host . '/daren/getRecomm?recomm_ids=' . implode(',', $sids) . '&channel=' . $channel;
		$json   = Utility::getUrlContents($url, 3, $header);
		$return = json_decode($json, True);
		$shares = array();
		if (is_array($return) && isset($return['status']) && $return['status'] == 1)
		{
			$shares = $return['share'];
		}
		return $shares;
	}
}
